package com.ledim.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.FocusDataBean;
import com.ledim.bean.LedimPicBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.ledimview.LedimBaseUserInfoView;
import com.ledim.ledimview.LedimBaseUserPowerView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.FastBlurUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.core.bean.IVideo;
import com.letv.tracker2.enums.EventType;
import java.util.HashMap;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by qjq on 16/8/18.
 * 个人中心页面
 */
public class PersonalActivity extends LeDimBaseActivity {

    private LedimBaseUserInfoView mBaseUserinfoView;
    private LedimBaseUserPowerView mBaseUserPowerView;

    private TextView tv_palyroom_name;
    private ImageView iv_play;
    private TextView tv_palyuser_name;
    private Button bt_focus_state;
    private SimpleDraweeView dv_playroom_bg;
    private TextView tv_playroom_over;
    private LinearLayout ll_personal_layout;
    private String uid;
    private int mRelation;
    private LoadingBar mLoadingBar;
    private ImageView iv_back;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_personal;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void onDestroy() {
        if (mLoadingBar != null) {
            mLoadingBar.dismiss();
        }
        super.onDestroy();
    }

    /**
     * @param context
     * @param uid
     *         跳转个人主页
     */
    public static void jumpPersonalHomePage(Context context, String uid) {
        if (!TextUtils.isEmpty(uid)) {
            Intent intent = new Intent(context, PersonalActivity.class);
            intent.putExtra(ConstantUtil.ID, uid);
            context.startActivity(intent);
            ((Activity) context).overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        }
    }

    /**
     * 初始化view
     */
    private void initView() {
        //获取LedimBaseUserInfoView
        mBaseUserinfoView = (LedimBaseUserInfoView) findViewById(R.id.ledim_base_userinfo_layout);
        mBaseUserinfoView.initSetting(null, true);

        //获取baseuserpowerview
        mBaseUserPowerView =
                (LedimBaseUserPowerView) findViewById(R.id.ledim_base_userpower_layout);
        mBaseUserPowerView.initSetting(true);

        ll_personal_layout = (LinearLayout) findViewById(R.id.ll_personal_layout);

        //放映厅room名字
        tv_palyroom_name = (TextView) findViewById(R.id.tv_palyroom_name);
        //播放
        iv_play = (ImageView) findViewById(R.id.iv_play);
        //放映厅用户名字
        tv_palyuser_name = (TextView) findViewById(R.id.tv_palyuser_name);
        //关注的状态
        bt_focus_state = (Button) findViewById(R.id.bt_focus_state);
        bt_focus_state.setOnClickListener(this);
        //放映厅的背景
        dv_playroom_bg = (SimpleDraweeView) findViewById(R.id.dv_playroom_bg);
        //放映结束
        tv_playroom_over = (TextView) findViewById(R.id.tv_playroom_over);

        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        getUserInfoFromId(getIntent().getStringExtra(ConstantUtil.ID));
    }

    /**
     * 通过用户ID查找用户信息
     *
     * @param id
     */
    private void getUserInfoFromId(String id) {
        if (mLoadingBar == null) {
            mLoadingBar = new LoadingBar(this);
        }
        ll_personal_layout.setVisibility(View.GONE);
        bt_focus_state.setVisibility(View.GONE);
        mLoadingBar.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .getUserInfoFromId(id)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<ChatRoomBean>>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onNext(BaseResultDataInfo<ChatRoomBean> chatRoomBean) {
                                     super.onNext(chatRoomBean);
                                     mLoadingBar.dismiss();
                                     if (chatRoomBean != null) {
                                         if (chatRoomBean.success) {
                                             ll_personal_layout.setVisibility(View.VISIBLE);
                                             bt_focus_state.setVisibility(View.VISIBLE);
                                             //成功
                                             //展示用户信息
                                             mBaseUserinfoView.setUserInfo(chatRoomBean.data.user);
                                             mBaseUserinfoView.setLayoutVisible();
                                             mBaseUserinfoView.setSignInvisible();
                                             mBaseUserPowerView.chooseGoldImage(chatRoomBean.data.user.coin, chatRoomBean.data.user.max_coin);
                                             mBaseUserPowerView.getSwordAndShow(chatRoomBean.data.user.power);
                                             setPlayRoomInfo(chatRoomBean.data);
                                         } else {
                                             //失败
                                             ToastUtil.toast(chatRoomBean.message);
                                         }
                                     }

                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     mLoadingBar.dismiss();
                                     LogUtil.e(e.getMessage());
                                 }
                             });
    }

    /**
     * 设置播放信息
     */
    private void setPlayRoomInfo(final ChatRoomBean chatRoomBean) {
        if (chatRoomBean != null) {
            tv_palyroom_name.setVisibility(View.VISIBLE);
            //关注状态判断
            mRelation = chatRoomBean.user.relation;
            setFocusBgByState(mRelation);
            //获取用户id
            uid = chatRoomBean.user.userId;
            //设置放映厅名称
            if (!TextUtils.isEmpty(chatRoomBean.name)) {
                tv_palyroom_name.setText(Html.fromHtml(chatRoomBean.name) + "的影院");
            }
            //放映状态判断
            if (chatRoomBean.status == 1) {
                //正在放映
                iv_play.setVisibility(View.VISIBLE);
                tv_palyuser_name.setVisibility(View.VISIBLE);
                tv_playroom_over.setVisibility(View.GONE);
                //设置背景
                LedimPicBean ledimPicBean = chatRoomBean.cover;
                if (ledimPicBean != null) {
                    if (!TextUtils.isEmpty(ledimPicBean.large)) {
                        handRoomBg(false, Uri.parse(ledimPicBean.large));
                    }
                }
                //设置放映的标题(播放按钮下面的文字)
                if (chatRoomBean.status == 1) {
                    if (chatRoomBean.current != null && chatRoomBean.current.length() > 0 &&
                            !chatRoomBean.current.equals("null")) {
                        tv_palyuser_name.setText(chatRoomBean.current.trim());

                    } else {
                        tv_palyuser_name.setText("洗脑循环中");
                    }
                } else {
                    tv_palyuser_name.setText("放映结束");
                }
                //播放按钮
                iv_play.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        IVideo roomVideo = new IVideo();
                        roomVideo.setmVid(0);
                        //上传数据
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("roomId", chatRoomBean.roomId);
                        LeDimAnalysisUtils.reportEvent(LeDimAnalysisUtils.ROOM_PAGE_CODE, EventType.Click, params);
                        if (chatRoomBean.user != null &&
                                !TextUtils.isEmpty(chatRoomBean.user.userId) &&
                                chatRoomBean.user.userId.equals(LedimSpUtils.getUid())) {
                            LetvSDK.getInstance()
                                   .playRoom(PersonalActivity.this, roomVideo, chatRoomBean, true, false);
                        } else {
                            LetvSDK.getInstance()
                                   .playRoom(PersonalActivity.this, roomVideo, chatRoomBean);
                        }

                    }
                });
            } else {
                //放映结束
                iv_play.setVisibility(View.GONE);
                tv_palyuser_name.setVisibility(View.GONE);
                tv_playroom_over.setVisibility(View.VISIBLE);
                //设置背景，然后在使用高斯模糊效果
                if (!TextUtils.isEmpty(chatRoomBean.cover.large)) {
                    handRoomBg(true, Uri.parse(chatRoomBean.cover.large));
                }
            }
        }
    }

    /**
     * 处理背景图片
     *
     * @param isNeedHand
     */
    private void handRoomBg(boolean isNeedHand, Uri imageUri) {
        if (isNeedHand) {
            //需要处理，加上高斯模糊效果
            Postprocessor redMeshPostprocessor = new BasePostprocessor() {
                @Override
                public String getName() {
                    return "redMeshPostprocessor";
                }

                @Override
                public void process(final Bitmap bitmap) {
                    //bitmap为下载的图片
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (bitmap != null) {
                                Bitmap blurBitmap = FastBlurUtil.toBlur(bitmap, 5);
                                dv_playroom_bg.setScaleType(ImageView.ScaleType.CENTER_CROP);
                                dv_playroom_bg.setImageBitmap(blurBitmap);
                            }
                        }
                    });
                }
            };
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(imageUri)
                                                      .setPostprocessor(redMeshPostprocessor)
                                                      .build();
            PipelineDraweeController controller =
                    (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                                                     .setImageRequest(request)
                                                     .setOldController(dv_playroom_bg.getController())
                                                     .build();
            dv_playroom_bg.setController(controller);
        } else {
            FrescoUtil.loadUrl(imageUri, dv_playroom_bg);
        }
    }

    /**
     * 根据状态刷新背景
     */
    private void setFocusBgByState(int focusState) {
        switch (focusState) {
            case ConstantUtil.NOT_FOCUS_STATE:
                bt_focus_state.setBackgroundResource(R.drawable.personal_focus);
                break;
            case ConstantUtil.ALREADY_FOCUS_STATE:
                bt_focus_state.setBackgroundResource(R.drawable.personal_already_focus);
                break;
            case ConstantUtil.TOGETHER_FOCUS_STATE:
                bt_focus_state.setBackgroundResource(R.drawable.personal_together_focus);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_focus_state:
                doFollowAction();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    public void doFollowAction() {

        LedimHttpObserver observer = new LedimHttpObserver<BaseResultDataInfo<FocusDataBean>>() {
            @Override
            public void onCompleted() {
                super.onCompleted();
            }

            @Override
            public void onNext(BaseResultDataInfo<FocusDataBean> data) {
                super.onNext(data);
                if (data != null) {
                    if (data.success) {
                        //成功
                        mRelation = data.data.type;
                        //更新下关注和粉丝的数量
                        mBaseUserinfoView.setFollowAndFansCounts(data.data.follow, data.data.fans);
                        setFocusBgByState(mRelation);
                    } else {
                        //失败
                        LedimApiServiceUtils.followFailMsg(mRelation);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                LogUtil.e(e.getMessage());
                LedimApiServiceUtils.followFailMsg(mRelation);
            }
        };
        switch (mRelation) {
            case ConstantUtil.NOT_FOCUS_STATE:
                LedimApiServiceUtils.requestFanAndFollowData(ConstantUtil.NOT_FOCUS_STATE, uid, observer);
                break;
            case ConstantUtil.ALREADY_FOCUS_STATE:
            case ConstantUtil.TOGETHER_FOCUS_STATE:
                LedimApiServiceUtils.requestFanAndFollowData(ConstantUtil.ALREADY_FOCUS_STATE, uid, observer);
                break;
        }

    }

}
